package org.detailsmatter.hudson;

import hudson.Extension;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.AbstractBuild;
import hudson.model.Hudson;
import hudson.tasks.junit.TestAction;
import hudson.tasks.junit.TestDataPublisher;
import hudson.tasks.junit.TestObject;
import hudson.tasks.junit.TestResult;
import hudson.tasks.junit.TestResultAction.Data;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;

public class ConcordionAnnotator extends TestDataPublisher {

	@Extension
	public static final class DescriptorImpl extends Descriptor<TestDataPublisher> {

		@Override
		public String getDisplayName() {
			return "Add concordion links in JUnit results";
		}
	}

	@DataBoundConstructor
	public ConcordionAnnotator() {
	}

	public static final class ConcordionAnnotatorAction extends TestAction {
		private final String workspacePath;
		private final String workspaceUrl;
		private final Pattern htmlPattern;

		public ConcordionAnnotatorAction(String workspacePath, String workspaceUrl) {
			this.workspacePath = appendSlashIfNeeded(workspacePath);
			this.workspaceUrl = appendSlashIfNeeded(workspaceUrl);
			this.htmlPattern = Pattern.compile("(.*\\.html)");
		}

		private String appendSlashIfNeeded(String path) {
			return path.endsWith("/") ? path : path + "/";
		}

		public String getIconFileName() {
			return null;
		}

		public String getDisplayName() {
			return null;
		}

		public String getUrlName() {
			return null;
		}

		@Override
		public String annotate(String text) {
			Matcher matcher = htmlPattern.matcher(text);
			StringBuilder result = new StringBuilder();
			int lastIndex = 0;

			while (matcher.find()) {
				result.append(text.substring(lastIndex, matcher.start()));

				String htmlPath = matcher.group();
				if (htmlPath.startsWith(workspacePath)) {
					result.append("<a href=\"");
					result.append(workspaceUrl);
					result.append(StringUtils.removeStart(htmlPath, workspacePath));
					result.append("\">").append(htmlPath).append("</a>");
				}
				lastIndex = matcher.end();
			}

			if (lastIndex < (text.length() - 1)) {
				result.append(text.substring(lastIndex));
			}
			return result.toString();
		}
	};

	@Override
	public Data getTestData(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, TestResult testResult) throws IOException,
			InterruptedException {
		final String workspacePath = build.getWorkspace().getRemote();
		final String workspaceUrl = Hudson.getInstance().getRootUrl() + build.getParent().getUrl() + "ws/";

		return new Data() {
			@Override
			public List<? extends TestAction> getTestAction(TestObject testObject) {
				return Arrays.asList(new ConcordionAnnotatorAction(workspacePath, workspaceUrl));
			}
		};
	}
}
